package com.diyunapp.xilinapp.fragments;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.diyunapp.xilinapp.R;
import com.diyunapp.xilinapp.adapters.RecycleViewSortsAdapter;
import com.diyunapp.xilinapp.adapters.SortsMiddleAdapter;
import com.diyunapp.xilinapp.adapters.SortsTopAdapter;
import com.diyunapp.xilinapp.bean.GoodsSortsBottomBean;
import com.diyunapp.xilinapp.bean.GoodsSortsMiddleBean;
import com.diyunapp.xilinapp.details.SearchResultActivity;
import com.diyunapp.xilinapp.details.SearchSetActivity;
import com.diyunapp.xilinapp.myapi.OnRecyclerViewItemClickListener;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * A simple {@link Fragment} subclass.
 */
public class SortFragment extends Fragment {


    @Bind(R.id.sort_search_ll)
    LinearLayout sortSearchLl;
    @Bind(R.id.goodssort_bottom_recylerView)
    RecyclerView goodssortBottomRecylerView;
    @Bind(R.id.goodssort_bottom_swiperefreshlayout)
    SwipeRefreshLayout goodssortBottomSwiperefreshlayout;
    @Bind(R.id.goodssort_middle_ListView)
    ListView goodssortMiddleListView;
    @Bind(R.id.goodssort_top_ListView)
    ListView goodssortTopListView;

    private LinearLayoutManager lineLayoutManager;
    private List<GoodsSortsBottomBean> sortsLists;
    private RecycleViewSortsAdapter recycleViewAdapter;

    private List<GoodsSortsMiddleBean> sortsMiddleLists;
    private SortsMiddleAdapter sMAdpter;

    private List<GoodsSortsMiddleBean> sortsTopLists;
    private SortsTopAdapter sTAdpter;

    private int bottom_selected = -1;
    private boolean lock_bottom = false;
    private int middle_selected = -1;
    private boolean lock_middle = false;

    private boolean isOnlyBottom = true;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_sort, container, false);
        ButterKnife.bind(this, view);
        initSortsView();
        getBottomSorts();
        return view;
    }

    private void initSortsView() {

        sortSearchLl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent searchInt = new Intent(getActivity(), SearchSetActivity.class);
                startActivity(searchInt);
            }
        });

        lineLayoutManager = new LinearLayoutManager(getActivity());
        sortsLists = new ArrayList<>();
        recycleViewAdapter = new RecycleViewSortsAdapter(sortsLists);
        goodssortBottomRecylerView.setLayoutManager(lineLayoutManager);
        goodssortBottomRecylerView.setAdapter(recycleViewAdapter);

        goodssortBottomSwiperefreshlayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Log.d("zhangxiaoxidebug", "invoke onRefresh...");
                if (isOnlyBottom) {
                    sortsLists.clear();
                    getBottomSorts();
                }
            }
        });

        recycleViewAdapter.setOnItemClickListener(new OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int data) {
                if(lock_bottom)
                {
                    return;
                }

                if (bottom_selected == data) {
                    bottom_selected = -1;
                    //再次点击当前选中项目时，隐藏掉二级和三级分类
                    goodssortTopListView.setVisibility(View.GONE);
                    goodssortMiddleListView.setVisibility(View.GONE);
                    bottomStateChange(false);
                    recycleViewAdapter.notifyDataSetChanged();
                    isOnlyBottom = true;
                } else {
                    bottom_selected = data;
                    lock_bottom = true;
                    getMiddleSorts();
                }
            }
        });

        sortsMiddleLists = new ArrayList<>();
        sMAdpter = new SortsMiddleAdapter(getActivity(), sortsMiddleLists);
        goodssortMiddleListView.setAdapter(sMAdpter);
        goodssortMiddleListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(lock_middle)
                {
                    return;
                }
                if (middle_selected == position) {
                    middle_selected = -1;
                    goodssortTopListView.setVisibility(View.GONE);
                    middleStateChange(false);
                    sMAdpter.notifyDataSetChanged();
                } else {
                    middle_selected = position;
                    lock_middle = true;
                    getTopSorts();
                }
            }
        });

        sortsTopLists = new ArrayList<>();
        sTAdpter = new SortsTopAdapter(getActivity(), sortsTopLists);
        goodssortTopListView.setAdapter(sTAdpter);
        goodssortTopListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent searchInt = new Intent(getActivity(), SearchResultActivity.class);
                searchInt.putExtra("SearchKeyType", "gc_id");
                searchInt.putExtra("SearchKeyWord", sortsTopLists.get(position).getSortId());
                searchInt.putExtra("SearchKeyAddion", sortsTopLists.get(position).getSortTitle());
                startActivity(searchInt);
            }
        });

    }

    private void bottomStateChange(boolean display) {
        if (display) {
            for (int i = 0; i < sortsLists.size(); i++) {
                sortsLists.get(i).setIfDisplay(true);
                sortsLists.get(i).setBeSelected(false);
            }
        } else {
            for (int i = 0; i < sortsLists.size(); i++) {
                sortsLists.get(i).setIfDisplay(false);
                sortsLists.get(i).setBeSelected(false);
            }
        }
    }

    private void middleStateChange(boolean display) {
        if (display) {
            for (int i = 0; i < sortsMiddleLists.size(); i++) {
                sortsMiddleLists.get(i).setIfDisplay(true);
                sortsMiddleLists.get(i).setBeSelected(false);
            }
        } else {
            for (int i = 0; i < sortsMiddleLists.size(); i++) {
                sortsMiddleLists.get(i).setIfDisplay(false);
                sortsMiddleLists.get(i).setBeSelected(false);
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    private void getBottomSorts() {
        String url = "http://www.xilingou.com/mobile/index.php?act=goods_class";
        Log.i("zhangxiaoxidebug", "getGoodsSorts....begin-------");
        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(500);
        http.send(HttpRequest.HttpMethod.GET, url, new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {

                        Log.i("zhangxiaoxidebug", "getIndex....onLoading");
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        Log.i("zhangxiaoxidebug", "getIndex....onSuccess");
                        goodssortBottomSwiperefreshlayout.setRefreshing(false);
                        int result = parseProject(responseInfo.result);
                        switch (result) {
                            case 1:
                                break;
                            case 2:
                                Toast.makeText(getActivity(), "没有子分类了！", Toast.LENGTH_LONG).show();
                                break;
                            case 0:
                                Toast.makeText(getActivity(), "读取数据失败！", Toast.LENGTH_LONG).show();
                                break;
                            default:
                                break;
                        }
                    }

                    @Override
                    public void onStart() {
                        goodssortBottomSwiperefreshlayout.setRefreshing(true);
                    }

                    private int parseProject(String result) {
                        Log.i("zhangxiaoxidebug", "sort_result=" + result);
                        try {
                            JSONObject jsObjectCode = new JSONObject(result);
                            int code = jsObjectCode.getInt("code");
                            if (code != 200) {
                                return 0;
                            }
                            JSONObject jsObjectData = jsObjectCode.getJSONObject("datas");
                            JSONArray jsArrayClass = jsObjectData.getJSONArray("class_list");
                            if (jsArrayClass.length() <= 0) {
                                return 2;
                            }
                            sortsLists.clear();
                            for (int i = 0; i < jsArrayClass.length(); i++) {
                                JSONObject jsObjectSort = jsArrayClass.getJSONObject(i);
                                String gc_id = jsObjectSort.getString("gc_id");
                                String gc_name = jsObjectSort.getString("gc_name");
                                String image = jsObjectSort.getString("image");
                                String text = jsObjectSort.getString("text");

                                sortsLists.add(new GoodsSortsBottomBean(gc_id, image, gc_name, text));
                            }
                            recycleViewAdapter.notifyDataSetChanged();

                        } catch (JSONException e) {
                            e.printStackTrace();
                            return 0;
                        }
                        return 1;
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        goodssortBottomSwiperefreshlayout.setRefreshing(false);
                        Log.i("zhangxiaoxidebug", "getIndex....onFailure");
                        Toast.makeText(getActivity(), "读取数据失败，请检查网络设置！", Toast.LENGTH_LONG).show();
                    }
                }
        );
    }

    private void getMiddleSorts() {
        String url = "http://www.xilingou.com/mobile/index.php?act=goods_class&gc_id=" + sortsLists.get(bottom_selected).getSortId();
        Log.i("zhangxiaoxidebug", "getMiddleSorts url=" + url);
        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(500);
        http.send(HttpRequest.HttpMethod.GET, url, new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {

                        Log.i("zhangxiaoxidebug", "getIndex....onLoading");
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        Log.i("zhangxiaoxidebug", "getIndex....onSuccess");
                        goodssortBottomSwiperefreshlayout.setRefreshing(false);
                        int result = parseProject(responseInfo.result);
                        switch (result) {
                            case 1:
                                break;
                            case 2:
                                Intent searchInt = new Intent(getActivity(), SearchResultActivity.class);
                                searchInt.putExtra("SearchKeyType", "gc_id");
                                searchInt.putExtra("SearchKeyWord", sortsLists.get(bottom_selected).getSortId());
                                searchInt.putExtra("SearchKeyAddion", sortsLists.get(bottom_selected).getSortTitle());
                                startActivity(searchInt);
                                break;
                            case 0:
                                Toast.makeText(getActivity(), "读取数据失败！", Toast.LENGTH_LONG).show();
                                break;
                            default:
                                break;
                        }
                    }

                    @Override
                    public void onStart() {

                    }

                    private int parseProject(String result) {
                        Log.i("zhangxiaoxidebug", "sort_result=" + result);
                        Log.i("zhangxiaoxidebug", "bottom_selected=" + bottom_selected);
                        try {
                            JSONObject jsObjectCode = new JSONObject(result);
                            int code = jsObjectCode.getInt("code");
                            if (code != 200) {
                                return 0;
                            }
                            JSONObject jsObjectData = jsObjectCode.getJSONObject("datas");
                            String sortString = jsObjectData.getString("class_list");
                            if (sortString.equals("0")) {
                                return 2;
                            }
                            JSONArray jsArrayClass = new JSONArray(sortString);
                            sortsMiddleLists.clear();
                            for (int i = 0; i < jsArrayClass.length(); i++) {
                                JSONObject jsObjectSort = jsArrayClass.getJSONObject(i);
                                String gc_id = jsObjectSort.getString("gc_id");
                                String gc_name = jsObjectSort.getString("gc_name");
                                JSONObject jsObjectList = jsObjectSort.getJSONObject("child_class");
                                String listStr = jsObjectList.getString("class_list");
                                String text;
                                if (listStr.equals("false")) {
                                    text = "";
                                } else {
                                    text = listStr;
                                }
                                sortsMiddleLists.add(new GoodsSortsMiddleBean(gc_id, gc_name, text));
                            }

                            goodssortTopListView.setVisibility(View.GONE);
                            goodssortMiddleListView.setVisibility(View.VISIBLE);
                            isOnlyBottom = false;
                            bottomStateChange(true);
                            sortsLists.get(bottom_selected).setBeSelected(true);
                            recycleViewAdapter.notifyDataSetChanged();
                            sMAdpter.notifyDataSetChanged();
                            lock_bottom = false;
                        } catch (JSONException e) {
                            e.printStackTrace();
                            return 0;
                        }
                        return 1;
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        goodssortBottomSwiperefreshlayout.setRefreshing(false);
                        lock_bottom = false;
                        Log.i("zhangxiaoxidebug", "getIndex....onFailure");
                        Toast.makeText(getActivity(), "读取数据失败，请检查网络设置！", Toast.LENGTH_LONG).show();
                    }
                }
        );
    }

    private void getTopSorts() {
        String url = "http://www.xilingou.com/mobile/index.php?act=goods_class&gc_id=" + sortsMiddleLists.get(middle_selected).getSortId();
        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(500);
        http.send(HttpRequest.HttpMethod.GET, url, new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {

                        Log.i("zhangxiaoxidebug", "getIndex....onLoading");
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        Log.i("zhangxiaoxidebug", "getIndex....onSuccess");
                        goodssortBottomSwiperefreshlayout.setRefreshing(false);
                        int result = parseProject(responseInfo.result);
                        switch (result) {
                            case 1:
                                break;
                            case 2:
                                Intent searchInt = new Intent(getActivity(), SearchResultActivity.class);
                                searchInt.putExtra("SearchKeyType", "gc_id");
                                searchInt.putExtra("SearchKeyWord", sortsMiddleLists.get(middle_selected).getSortId());
                                searchInt.putExtra("SearchKeyAddion", sortsMiddleLists.get(middle_selected).getSortTitle());
                                startActivity(searchInt);
                                break;
                            case 0:
                                Toast.makeText(getActivity(), "读取数据失败！", Toast.LENGTH_LONG).show();
                                break;
                            default:
                                break;
                        }
                    }

                    @Override
                    public void onStart() {

                    }

                    private int parseProject(String result) {
                        Log.i("zhangxiaoxidebug", "sort_result=" + result);
                        Log.i("zhangxiaoxidebug", "middle_selected=" + middle_selected);
                        try {
                            JSONObject jsObjectCode = new JSONObject(result);
                            int code = jsObjectCode.getInt("code");
                            if (code != 200) {
                                return 0;
                            }
                            JSONObject jsObjectData = jsObjectCode.getJSONObject("datas");

                            String sortString = jsObjectData.getString("class_list");
                            if (sortString.equals("0")) {
                                return 2;
                            }
                            JSONArray jsArrayClass = new JSONArray(sortString);
                            sortsTopLists.clear();
                            for (int i = 0; i < jsArrayClass.length(); i++) {
                                JSONObject jsObjectSort = jsArrayClass.getJSONObject(i);
                                String gc_id = jsObjectSort.getString("gc_id");
                                String gc_name = jsObjectSort.getString("gc_name");
                                String text = jsObjectSort.getString("gc_name");

                                sortsTopLists.add(new GoodsSortsMiddleBean(gc_id, gc_name, text));
                            }
                            goodssortTopListView.setVisibility(View.VISIBLE);
                            middleStateChange(true);
                            sortsMiddleLists.get(middle_selected).setBeSelected(true);
                            sMAdpter.notifyDataSetChanged();
                            sTAdpter.notifyDataSetChanged();
                            lock_middle= false;
                        } catch (JSONException e) {
                            e.printStackTrace();
                            return 0;
                        }
                        return 1;
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        goodssortBottomSwiperefreshlayout.setRefreshing(false);
                        lock_middle = false;
                        Log.i("zhangxiaoxidebug", "getIndex....onFailure");
                        Toast.makeText(getActivity(), "读取数据失败，请检查网络设置！", Toast.LENGTH_LONG).show();
                    }
                }
        );
    }
}
